package cn.logicalthing.demo.web.controller;

import cn.logicalthing.demo.web.bean.DBShoppingCar;
import cn.logicalthing.demo.web.error.CommonErrorCode;
import cn.logicalthing.demo.web.error.RequestBean;
import com.core.bean.*;
import com.core.dao.mybatismysql.GoodsDao;
import com.core.dao.mybatismysql.UserDao;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class ShoppingController {

    @PostMapping("/addCar")
    public RequestBean addCar(String goodsId, int count, String userId, String shopId) throws Exception {
        ShoppingCar car = DBShoppingCar.getCar();
        GoodsDao goodsDao = new GoodsDao();
        UserDao userDao = new UserDao();
        try {
            Goods goods = goodsDao.findEntityById(goodsId);
            ShoppingCarCheck check = new ShoppingCarCheck();
            if (!check.check(car, goods))
                throw new Exception("....");
            car.add(goods, count);
            User user = userDao.findEntityById(userId);
            car.save(user, shopId, goodsId, count);
            return new RequestBean("添加成功");
        } catch (Exception e) {
            return new RequestBean(CommonErrorCode.E_2001);
        }
    }

    @PostMapping("/remove")
    public RequestBean remove(String goodsId, String userId, String shopId,Integer count) throws Exception {
        ShoppingCar car = DBShoppingCar.getCar();
        if (car == null)
            return new RequestBean(CommonErrorCode.E_2000);
        try {
            GoodsDao goodsDao = new GoodsDao();
            Goods goods = goodsDao.findEntityById(goodsId);
            car.remove(goods);
            UserDao userDao = new UserDao();
            User user = userDao.findEntityById(userId);
            car.save(user, shopId, goodsId, count);
            return new RequestBean("移除成功");
        } catch (Exception e) {
            return new RequestBean(CommonErrorCode.E_2002);
        }
    }

    @PostMapping("/listCar")
    public List<CarItem> listCar() throws Exception {
        ShoppingCar car = DBShoppingCar.getCar();
        return car.getItems();
    }

    public int getTotalCount() {
        int count = 0;
        ShoppingCar car = DBShoppingCar.getCar();
        if (car == null)
            return count;
        for (int i = 0; i < car.getItems().size(); i++) {
            count += car.getItems().get(i).getCount();
        }
        return count;
    }
}
